package com.zwy;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

// 编译
// javac -encoding UTF-8 -classpath .;D:/workspace/springboot2/boot10-redis-jedis/src/test/java/jedis-4.1.0.jar;D:/workspace/springboot2/boot10-redis-jedis/src/test/java/commons-pool2-2.11.1.jar com/zwy/SentinelTestMain.java
// 运行
// java -Djava.ext.dirs=./ com/zwy/SentinelTestMain
public class SentinelTestMain {

    public static void main(String[] args) throws IOException {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(10);
        jedisPoolConfig.setMaxIdle(5);
        jedisPoolConfig.setMinIdle(5);

        // 哨兵信息
        Set<String> sentinels = new HashSet<>(Arrays.asList("172.17.0.13:26379"));
        // 创建连接池
        JedisSentinelPool pool = new JedisSentinelPool("mymaster", sentinels, jedisPoolConfig);
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line = null;
        while((line = reader.readLine()) != null){
            if("END".equalsIgnoreCase(line)){
                break;
            }
            try(Jedis jedis = pool.getResource()){
                // 执行两个命令
                String oldValue = jedis.getSet("token", line);
                System.out.println("旧的值:" +oldValue);
            } catch (JedisConnectionException e){
                pool = new JedisSentinelPool("mymaster", sentinels, jedisPoolConfig);
                System.out.println("重新连接");
            }
        }
    }
}
